<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>图形平移</title>
    <script src="test.js"></script>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      canvas {
        margin: 50px auto 0;
        display: block;
        background: yellow;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="400px" height="400px"></canvas>
    <canvas id="tutorial" width="150" height="150"></canvas>

    <script>
      // 1获取webgl
      const canvas = document.getElementById('canvas')
      const gl = canvas.getContext('webgl')

      // 3.定义顶点着色器和片元着色器
      const vsSource = `
        attribute vec4 aPosition;
        attribute float aScale;
        void main(){
        gl_Position=vec4(aPosition.x*aScale,aPosition.y,aPosition.z ,1);
        gl_PointSize=10.0;
        }`
      const fsSource = `
        void main(){
         gl_FragColor = vec4(1.0,0.0,0.0,1.0);
        }`

      // 2.初始化webgl
      const program = initShader(gl, vsSource, fsSource)
      gl.useProgram(program)
      // 4.获取aPosition的值
      const aPosition = gl.getAttribLocation(program, 'aPosition')
      const aScale = gl.getAttribLocation(program, 'aScale')
      //   5.创建缓存区
      function drawHeart() {
        var canvas = document.getElementById('tutorial')
        if (canvas.getContext) {
          var ctx = canvas.getContext('2d')
          ctx.fillStyle = 'rgb(200,0,0)'
          // 二次贝塞尔曲线
          ctx.beginPath()
          ctx.moveTo(75, 40)
          ctx.bezierCurveTo(75, 37, 70, 25, 50, 25)
          ctx.bezierCurveTo(20, 25, 20, 62.5, 20, 62.5)
          ctx.bezierCurveTo(20, 80, 40, 102, 75, 120)
          ctx.bezierCurveTo(110, 102, 130, 80, 130, 62.5)
          ctx.bezierCurveTo(130, 62.5, 130, 25, 100, 25)
          ctx.bezierCurveTo(85, 25, 75, 37, 75, 40)
          ctx.fill()
        } else {
          console.log('不支持canvas')
        }
      }
      drawHeart()
      const points = new Float32Array([-0.5, -0.5, 0.5, -0.5, 0.0, 0.5])
      const buffer = gl.createBuffer()
      if (!buffer) {
        console.log('创建缓冲区对象失败！')
      }
      gl.bindBuffer(gl.ARRAY_BUFFER, buffer)
      gl.bufferData(gl.ARRAY_BUFFER, points, gl.STATIC_DRAW)
      // 5.指定 uniform 的存储地址，四个分量
      gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, 0, 0)
      gl.enableVertexAttribArray(aPosition)
      // 清除颜色缓冲区
      gl.clear(gl.COLOR_BUFFER_BIT)
      let x = 1
      setInterval(() => {
        x += 0.1
        if (x > 2) {
          x = 2
        }
        gl.vertexAttrib1f(aScale, x)
        gl.drawArrays(gl.TRIANGLES, 0, 3) //重新绘制
      }, 60)
    </script>
  </body>
</html>
